package com.example.test.controller;
import com.example.test.module.PredResponse;
import com.example.test.module.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

@RestController
public class LstmController {
    private long lastTimeFileSize = 0; // 上次文件大小
//    private OSInfo.OSType osType = OSInfo.getOSType(); // 操作系统类型
    private String osType = System.getProperty("os.name").toLowerCase();
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private String file_path = "C:\\Users\\19161\\Desktop\\ju.txt";
    private File file = new File(file_path);
    // 实时输出日志信息
    @GetMapping("/readFile")
    public void readFile() {
        while (true) {
            boolean EndFlag = false;
            try {
                RandomAccessFile randomFile = new RandomAccessFile(file, "r");
                randomFile.seek(lastTimeFileSize);
                String tmp = null;
                while ((tmp = randomFile.readLine()) != null) {
                    tmp.replaceAll("\\s*", "");
                    if(tmp!=""){
                        System.out.println(dateFormat.format(new Date()) + "\t" + tmp);
                    }
                    if (tmp.contains("Finish")) {
                        EndFlag = true;
                    }
                }
                lastTimeFileSize = randomFile.length();
                if(EndFlag == true)
                    return;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private static final Logger log = LoggerFactory.getLogger(LstmController.class);

    @GetMapping("/lstm")
    public Response lstm(HttpServletRequest request) {
        log.info("LstmController");
        // 打印请求参数
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String name = enu.nextElement();
            String value = request.getParameter(name);
            System.out.println(name + ":" + value);
        }
        String model = request.getParameter("model");
        String dataType = request.getParameter("datatype");
        String dataSet = request.getParameter("dataset");

        try {
            Process process = null;
            String txtPath = "";
            // windows
            if(osType.contains("win")) {
                System.out.println("Windows");
                if(model.equals("LS-LSTM")){
                    txtPath = String.format("E:\\LS_LSTM\\predDir\\%s_y_pred.txt", dataType);
                    List<String> params = new ArrayList<String>();
                    params.add("cmd");
                    params.add("/c");
                    params.add("python");
                    params.add("lstmNet-pred.py");
                    params.add(request.getParameter("datatype"));
                    params.add(request.getParameter("dataset"));
                    ProcessBuilder processBuilder = new ProcessBuilder(params);
                    //            ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", "python lstmNet-pred.py tls tls_5000");
                    System.out.println(processBuilder.command());
                    processBuilder.directory(new File("E:\\LS_LSTM"));
                    process = processBuilder.start();
                }
                else{
                    // 有待完善
                    return new Response(500, "error");
                }
            }

            // Linux
//          Process process = new ProcessBuilder("/bin/sh", "-c", "ls -l").start();
            else{
                if(model.equals("LS-LSTM")) {
                    txtPath = String.format("/home/wzj/LS_LSTM_proj/resDir/%s_y_pred.txt",dataType);
                    List<String> params = new ArrayList<String>();
//                params.add("/bin/sh");
//                params.add("-c");
                    params.add("python3");
                    params.add("lstmNet-pred.py");
                    params.add(request.getParameter("datatype"));
                    params.add(request.getParameter("dataset"));
                    ProcessBuilder processBuilder = new ProcessBuilder(params);
                    //            ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", "python lstmNet-pred.py tls tls_5000");
                    System.out.println(model+"调用python");
                    processBuilder.redirectErrorStream(true);
                    processBuilder.directory(new File("/home/wzj/LS_LSTM_proj"));
                    process = processBuilder.start();
                } else if (model.equals("Fs-Net")) {
                    txtPath = String.format("/home/wzj/LS_LSTM_proj/resDir/%s_y_pred.txt",dataType);
                    List<String> params = new ArrayList<String>();
                    params.add("python3");
                    params.add("fsNet-pred.py");
                    params.add(request.getParameter("datatype"));
                    params.add(request.getParameter("dataset"));
                    ProcessBuilder processBuilder = new ProcessBuilder(params);
                    //            ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", "python lstmNet-pred.py tls tls_5000");
                    System.out.println("调用python");
                    processBuilder.redirectErrorStream(true);
                    processBuilder.directory(new File("/home/wzj/FS-Net"));
                    process = processBuilder.start();
                } else if (model.equals("LS-CapsNet")) {
                    txtPath = String.format("/home/wzj/LS_LSTM_proj/resDir/%s_y_pred.txt",dataType);
                    List<String> params = new ArrayList<String>();
                    params.add("python3");
                    params.add("capNet-pred.py");
                    params.add(request.getParameter("datatype"));
                    params.add(request.getParameter("dataset"));
                    ProcessBuilder processBuilder = new ProcessBuilder(params);
                    //            ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", "python lstmNet-pred.py tls tls_5000");
                    System.out.println("调用python");
                    processBuilder.redirectErrorStream(true);
                    processBuilder.directory(new File("/home/wzj/LS-CapsNet"));
                    process = processBuilder.start();
                } else{
                    // 有待完善
                    return new Response(500, "error");
                }
            }

            double time_double = 0;
            // 获取进程的输出流
            Boolean Endflag = false;
            BufferedReader br = null;
            if(osType.contains("win"))
                br = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
            else
                br = new BufferedReader(new InputStreamReader(process.getInputStream(), "utf-8"));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                if (line.contains("time")) {
                    // 获取时间
                    String[] time = line.split(":");
                    // 时间转换为double
                    time_double = Double.parseDouble(time[1]);
                    time_double = (double)Math.round(time_double * 100) / 100;
                    Endflag = true;
                    System.out.println("** Finish all **");
                }
            }
            if(Endflag == true)
            {
                process.destroy();
                File predfile = new File(txtPath);
                // 获取predfile文件行数
                int lineNum = 0;
                try {
                    BufferedReader br1 = new BufferedReader(new FileReader(predfile));
                    while ((line = br1.readLine()) != null) {
                        lineNum++;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 读取y_pred.txt 保存到数组
                PredResponse[] predResponse = new PredResponse[lineNum];
                // 读取predfile文件按行写入predResponse数组
                BufferedReader br1 = null;
                if(osType.contains("win"))
                    br1 = new BufferedReader(new InputStreamReader(new FileInputStream(predfile), "GBK"));
                else
                    br1 = new BufferedReader(new InputStreamReader(new FileInputStream(predfile), "utf-8"));
                String line1;
                int i = 0;
                while ((line1 = br1.readLine()) != null) {
                    String[] str = line1.split("\t");
                    // str[1]转换为float并转换为百分数
                    float score = Float.parseFloat(str[1]) * 100;
                    score = (float) (Math.round(score * 10)) / 10;
//                    System.out.println(str[0] + "\t" + score);
                    predResponse[i] = new PredResponse(str[0], score);
                    i++;
                }
                Response response = new Response(200, predResponse, String.valueOf(time_double));
                return response;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Response(500, "error");
    }
}
